package com.weishe.util;


import java.util.ArrayList;
import java.util.List;

public class Utils {

	public static List<String> country=new ArrayList<String>();
	
	public static final String IP_REGEX="([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
	
	static {
		country.add("cn");
		country.add("hk");
		country.add("us");
	}
	
	public static final String[] SITE_HOSTS={
		"yihaodian.com",
		"yihaomall.com",
		"111.com.cn",
		"1mall.com"		
	};
	
	public static String getHostFromURL(String s) {
		if (s == null||s.trim().length()==0) { return null; }

		String temp=s.trim();
		String[] prefix={"http://", "https://","ftp://"};
		for(String p:prefix){
			if(temp.startsWith(p)){
				temp=temp.substring(p.length()).trim();
			}
		}
		
		String host = multipleSplit(temp, "/", "[?]", ":", "%");
		if(host==null){
			return "Invalid URL";
		}

		if(host.matches(IP_REGEX)){
			return host;
		}		
		String[] field = host.split("[.]");
		int len=field.length;
		if(field.length<2)
			return host;
		
		if((country.contains(field[len-1].toLowerCase())) && len>2 && (!field[len-3].equals("www"))){
			return field[len-3]+"."+field[len-2] +"."+ field[len-1];
		}else{
			return field[len-2]+"."+field[len-1];
		}
	}
	public static String multipleSplit(final String s, String... vars) {
		if (s == null ||s.trim().length()==0) { return null; }
		String dest=s.trim();		
		for(String var :vars){
			if(var==null||var.trim().length()==0){
				break;
			}
			int pos=0;
			String[] parse= var.trim().split("~");
			if(parse.length>2|| parse.length<1){
				return null;
			}
			if(parse.length==2){
				pos=Integer.parseInt(parse[1]);
			}
			String[] arr=dest.split(parse[0]);
			if(arr.length>pos){
				dest=dest.split(parse[0])[pos];	
			}else{
				return null;
			}					
		}
		return dest;
	}
	public static void main(String[] args) {
		System.out.println(getHostFromURL("www.qq.com:8080"));
	}
}
